package com.drive.controller;

import com.drive.bean.Student;
import com.drive.constant.MessageConstant;
import com.drive.entity.PageResult;
import com.drive.entity.QueryPageBean;
import com.drive.entity.Result;
import com.drive.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 往
 * 学员管理
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    public StudentService studentService;

    //新增学员
    @RequestMapping("/add")
    public Result addStudent(@RequestBody Student student){
        try{
             studentService.add(student);
        }catch (Exception e){
            return new Result(false, MessageConstant.ADD_STUDENT_FAIL);
        }
        return new Result(true,MessageConstant.ADD_STUDENT_SUCCESS);
    }
    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
            //将分页查询到的数据封装到PageResult中
            PageResult pageResult = studentService.pageQuery(
                        queryPageBean.getCurrentPage(),
                        queryPageBean.getPageSize(),
                        queryPageBean.getQueryString());

            return pageResult;

    }
    //删除
    @RequestMapping("/delete")
    public Result deleteStudent(Integer id){
        try {
            studentService.delete(id);
        }catch (Exception e){
            return new Result(false,MessageConstant.DELETE_STUDENT_FAIL);
        }
        return new Result(true,MessageConstant.DELETE_STUDENT_SUCCESS);
    }

    //根据id查询
    @RequestMapping("/findById")
    public Result findById(Integer id){
        try{
            Student student = (Student) studentService.findById(id);
            return new Result(true,MessageConstant.QUERY_STUDENT_SUCCESS,student);
        }catch (Exception e){
            return new Result(false,MessageConstant.QUERY_STUDENT_FAIL);
        }
    }

    //编辑学员
    @RequestMapping("/edit")
    public Result edit(@RequestBody Student student){
        try{
            studentService.edit(student);
        }catch (Exception e){
            return new Result(false,MessageConstant.EDIT_STUDENT_FAIL);
        }
        return new Result(true,MessageConstant.EDIT_STUDENT_SUCCESS);

    }

    //查询所有学员信息
    @RequestMapping("/findAll")
    public Result findAll(){
        try{
            List<Student> studentList = studentService.findAll();
            return new Result(true,MessageConstant.QUERY_STUDENT_SUCCESS,studentList);
        }catch (Exception e){
            return new Result(false,MessageConstant.QUERY_STUDENT_FAIL);
        }
    }
}
